﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class DataBase_Controles_LoginSearch : System.Web.UI.UserControl
{
    BO.Usuarios objRegistro;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            configuraPagina();
    }

    private void configuraPagina()
    {
        if (Session["usuarioLogado"] != null)
            pnlLogin.Visible = false;
        else
            pnlLogin.Visible = true;
    }

    private bool validaCampos()
    {
        if (txtLogin.Text.Length == 0)
        {
            lblMsg.Text = "Prencha o campo Nome de Usuário";
            return false;
        }
        else if (txtSenha.Text.Length == 0)
        {
            lblMsg.Text = "Prencha o campo Senha";
            return false;
        }
        else
        {
            return true;
        }
    }

    protected void btn_login_Click(object sender, EventArgs e)
    {
        if (validaCampos())
        {
            objRegistro = new BO.Usuarios();
            objRegistro.objVO.Login = txtLogin.Text;
            objRegistro.objVO.Senha = txtSenha.Text;

            if (objRegistro.getLogin())
            {
                Session.Add("usuarioLogado", objRegistro.objVO);
                Session.Add("cohortAtiva", objRegistro.objVO.IdUnidade);

                FormsAuthentication.RedirectFromLoginPage("Administrador", true);

                if (!string.IsNullOrEmpty(Request.QueryString["redirectUrl"]))
                    Response.Redirect(Request.QueryString["redirectUrl"]);
                else
                    Response.Redirect(Request.Path);
            }
            else
            {
                lblMsg.Text = "Login ou senha inválido(s).";
            }
        }
    }
}